from flask import Flask
from flask import request
from flask import jsonify
import random

app=Flask(__name__)

def generate_random_string(length, num_strings, use_numbers, use_lower_case, use_upper_case, use_special_chars):
    # Create a list of characters to choose from
    chars = []
    if use_numbers:
        chars += [str(i) for i in range(10)]
    if use_lower_case:
        chars += [chr(i) for i in range(97, 123)]
    if use_upper_case:
        chars += [chr(i) for i in range(65, 91)]
    if use_special_chars:
         chars += ['!','@','#','$']
            
    # Generate the strings
    strings = []
    for _ in range(num_strings):
        string = ''
        for _ in range(length):
            string += random.choice(chars)
        strings.append(string)
    
    return strings


@app.route('/')
def index():
    return '<h1>Hello World! From Flask!</h1>'


@app.route('/getrandomstr', methods=['POST'])
def getrandomstr():
    if request.method == 'POST':
        data_json=request.get_json()
            
         ##get parameters,获取来自客户端的信息；
        intlen=data_json.get("intlen")
        intnum=data_json.get("intnum")
        withnum=data_json.get("withnum")
        withlow=data_json.get("withlow")
        withup=data_json.get("withup")
        withspecial=data_json.get("withspecial")
            
        ##请求的随机数长度过长，数量过多则返回fail;
        if intlen>30 or intnum >1000:
            return jsonify(data=[], datalen=0, msg="fail")
            
        strings=[]
        ##根据客户端信息调用生成随机数生成;
        strings=generate_random_string(intlen, intnum, withnum, withlow, withup, withspecial)
        datalen=len(strings)
            
        if datalen>0:
            return jsonify(data=strings, datalen=datalen, msg="success")
        else:
            return jsonify(data=[], datalen=0, msg="fail")
